package com.ice.work.moment.oauth.service;

import com.google.common.collect.Lists;
import com.honeybee.cloud.framework.common.enums.DataStatusEnum;
import com.honeybee.cloud.framework.oauth.authority.OauthAuthority;
import com.honeybee.cloud.framework.oauth.user.OauthUser;
import com.ice.work.moment.facade.user.model.Resource;
import com.ice.work.moment.facade.user.model.User;
import com.ice.work.moment.oauth.dao.resource.ResourceRepository;
import com.ice.work.moment.oauth.dao.user.UserRepository;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * @Description
 * @Author DELL
 * @Create 2018-12-13
 * @Since 1.0.0
 */
@NoArgsConstructor
@Component
public class OauthUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ResourceRepository resourceRepository;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userRepository.findByMobileAndDataStatus(s, DataStatusEnum.VALID.key);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("登录名不存在");
        }
        OauthUser oauthUser = new OauthUser();
        List<Resource> resourceList = resourceRepository.findByUserIdAndDataStatus(user.getId(), DataStatusEnum.VALID.key);
        oauthUser.setUsername(user.getMobile());
        oauthUser.setPassword(user.getPassword());
        oauthUser.setEnabled(true);
        oauthUser.setAccountNonExpired(true);
        oauthUser.setAccountNonLocked(true);
        oauthUser.setUserId(user.getId());
        if (CollectionUtils.isEmpty(resourceList)) {
            return oauthUser;
        }
        List<OauthAuthority> authorityList = Lists.newArrayList();
        for (Resource resource : resourceList) {
            OauthAuthority authority = new OauthAuthority();
            authority.setAuthority(resource.getCode());
            authorityList.add(authority);
        }
        oauthUser.setAuthorities(authorityList);
        return oauthUser;
    }
}
